<?php

/**
 * SocialEnginePro
 *
 * @category   Application_Extensions
 * @package    
 * @author     Azim
 */

/**
 * @category   Application_Extensions
 * @package    
 */
class Tv_Model_Tv extends Core_Model_Item_Abstract {

    public function setPhoto($photo) {
        if ($photo instanceof Zend_Form_Element_File) {
            $file = $photo->getFileName();
        } else if (is_array($photo) && !empty($photo['tmp_name'])) {
            $file = $photo['tmp_name'];
        } else if (is_string($photo) && file_exists($photo)) {
            $file = $photo;
        } else {
            throw new Group_Model_Exception('invalid argument passed to setPhoto');
        }

        $name = basename($file);
        $path = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'temporary';
        $params = array(
            'parent_type' => $this->getType(),
            'parent_id' => $this->getIdentity()
        );

        // Save
        $storage = Engine_Api::_()->storage();

        // Resize image (main)
        $image = Engine_Image::factory();
        $image->open($file)
                ->resize(720, 720)
                ->write($path . '/m_' . $name)
                ->destroy();

        // Resize image (profile)
        $image = Engine_Image::factory();
        $image->open($file)
                ->resize(200, 400)
                ->write($path . '/p_' . $name)
                ->destroy();

        // Resize image (normal)
        $image = Engine_Image::factory();
        $image->open($file)
                ->resize(140, 160)
                ->write($path . '/in_' . $name)
                ->destroy();

        // Resize image (icon)
        $image = Engine_Image::factory();
        $image->open($file);

        $size = min($image->height, $image->width);
        $x = ($image->width - $size) / 2;
        $y = ($image->height - $size) / 2;

        $image->resample($x, $y, $size, $size, 48, 48)
                ->write($path . '/is_' . $name)
                ->destroy();

        // Store
        $iMain = $storage->create($path . '/m_' . $name, $params);
        $iProfile = $storage->create($path . '/p_' . $name, $params);
        $iIconNormal = $storage->create($path . '/in_' . $name, $params);
        $iSquare = $storage->create($path . '/is_' . $name, $params);

        $iMain->bridge($iProfile, 'thumb.profile');
        $iMain->bridge($iIconNormal, 'thumb.normal');
        $iMain->bridge($iSquare, 'thumb.icon');

        // Remove temp files
        @unlink($path . '/p_' . $name);
        @unlink($path . '/m_' . $name);
        @unlink($path . '/in_' . $name);
        @unlink($path . '/is_' . $name);

        // Update row
        $this->modified_date = date('Y-m-d H:i:s');
        $this->photo_id = $iMain->file_id;
        $this->save();

        return $this;
    }

    public function getHref($params = array()) {
        $params = array_merge(array(
            'route' => 'tv_specific',
            'reset' => true,
            'tv_id' => $this->tv_id,
                ), $params);

        $route = $params['route'];
        $reset = $params['reset'];
        unset($params['route']);
        unset($params['reset']);
        return Zend_Controller_Front::getInstance()->getRouter()
                        ->assemble($params, $route, $reset);
    }

    public function getContent($view = false, $params = array()) {
        $session = new Zend_Session_Namespace('mobile');
        $mobile = $session->mobile;

        // if video type is youtube
        if ($this->type == 1) {
            $videoEmbedded = $this->compileYouTube($this->tv_id, $this->code, $view, $mobile);
        }
        // if video type is vimeo
        if ($this->type == 2) {
            $videoEmbedded = $this->compileVimeo($this->tv_id, $this->code, $view, $mobile);
        }
        if ($this->type == 4) {
            $videoEmbedded = $this->compileStream($this->body);
        }





        return $videoEmbedded;
    }

    public function compileStream($body) {
        $embedded = '<object codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" classid="clsid:6bf52a52-394a-11d3-b153-00c04f79faa6" height="330" width="384">
  <param name="ShowControls" value="1">
    <param name="ShowAudioControls" value="1">
    <param name="ShowPositionControls" value="0">
    <param name="ShowTracker" value="0">
    <param name="ShowStatusBar" value="1">
    <param name="ShowDisplay" value="0">
    <param name="DefaultFrame" value="Slide">
    <param name="Autostart" value="1">
    <param name="EnableContextMenu" value="false">
    <param name="FileName" value="' . $body . '" />
<embed type="application/x-mplayer2" pluginspage="http://www.microsoft.com/Windows/
	MediaPlayer/download/default.asp" src="' . $body . '" name="MMPlayer1" autostart="1" showcontrols="1" showdisplay="0" showstatusbar="1" defaultframe="Slide" width="640" height="420"></embed>
</object>';

        return $embedded;
    }

    public function compileYouTube($tv_id, $code, $view, $mobile = false) {
        //560 x 340
        //legacy youtube embed code
        if (!$mobile) {
            $embedded = '
      <object width="' . ($view ? "560" : "425") . '" height="' . ($view ? "340" : "344") . '"">
      <param name="movie" value="http://www.youtube.com/v/' . $code . '&color1=0xb1b1b1&color2=0xcfcfcf&hl=en_US&feature=player_embedded&fs=1"/>
      <param name="allowFullScreen" value="true"/>
      <param name="allowScriptAccess" value="always"/>
      <embed src="http://www.youtube.com/v/' . $code . '&color1=0xb1b1b1&color2=0xcfcfcf&hl=en_US&feature=player_embedded&fs=1' . ($view ? "" : "&autoplay=1") . '" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="' . ($view ? "560" : "425") . '" height="' . ($view ? "340" : "344") . '" wmode="transparent"/>
      <param name="wmode" value="transparent" />
      </object>';
        } else {
            $autoplay = !$mobile && !$view;

            $embedded = '
        <iframe
        title="YouTube video player"
        id="videoFrame' . $tv_id . '"
        class="youtube_iframe' . ($view ? "_big" : "_small") . '"' .
                    /*
                      width="'.($view?"560":"425").'"
                      height="'.($view?"340":"344").'"
                     */'
        src="http://www.youtube.com/embed/' . $code . '?wmode=opaque' . ($autoplay ? "&autoplay=1" : "") . '"
        frameborder="0"
        allowfullscreen=""
        scrolling="no">
        </iframe>
        <script type="text/javascript">
          en4.core.runonce.add(function() {
            var doResize = function() {
              var aspect = 16 / 9;
              var el = document.id("videoFrame' . $tv_id . '");
              var parent = el.getParent();
              var parentSize = parent.getSize();
              el.set("width", parentSize.x);
              el.set("height", parentSize.x / aspect);
            }
            window.addEvent("resize", doResize);
            doResize();
          });
        </script>
      ';
        }

        return $embedded;
    }

    public function compileVimeo($tv_id, $code, $view, $mobile = false) {
        //640 x 360

        if (!$mobile) {
            $embedded = '
      <object width="' . ($view ? "560" : "425") . '" height="' . ($view ? "340" : "344") . '"">
      <param name="allowfullscreen" value="true"/>
      <param name="allowscriptaccess" value="always"/>
      <param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' . $code . '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" />
      <embed src="http://vimeo.com/moogaloop.swf?clip_id=' . $code . '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1' . ($view ? "" : "&amp;autoplay=1") . '" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' . ($view ? "640" : "400") . '" height="' . ($view ? "360" : "230") . '" wmode="transparent"/>
      <param name="wmode" value="transparent" />
      </object>';
        } else {
            $autoplay = !$mobile && !$view;

            $embedded = '
        <iframe
        title="Vimeo video player"
        id="videoFrame' . $tv_id . '"
        class="vimeo_iframe' . ($view ? "_big" : "_small") . '"' .
                    /*
                      width="'.($view?"640":"400").'"
                      height="'.($view?"360":"230").'"
                     */'
        src="http://player.vimeo.com/video/' . $code . '?title=0&amp;byline=0&amp;portrait=0&amp;wmode=opaque' . ($autoplay ? "&amp;autoplay=1" : "") . '"
        frameborder="0"
        allowfullscreen=""
        scrolling="no">
        </iframe>
        <script type="text/javascript">
          en4.core.runonce.add(function() {
            var doResize = function() {
              var aspect = 16 / 9;
              var el = document.id("videoFrame' . $tv_id . '");
              var parent = el.getParent();
              var parentSize = parent.getSize();
              el.set("width", parentSize.x);
              el.set("height", parentSize.x / aspect);
            }
            window.addEvent("resize", doResize);
            doResize();
          });
        </script>
        ';
        }

        return $embedded;
    }

    public function getSimilarTv() {
        $table = Engine_Api::_()->getDbtable('tvs', 'tv');
        return $table->select()
                        ->where('title or description LIKE ?', '%' . $this->title . '%')
                        ->where('tv_id <>?', $this->tv_id);
    }

    public function isFavourite() {
        $table = Engine_Api::_()->getDbtable('favourites', 'tv');
        $row = $table->select()
                ->from($table->info('name'), new Zend_Db_Expr('COUNT(*)'))
                ->where('tv_id =?', $this->tv_id)
                ->where('user_id =?', Engine_Api::_()->user()->getViewer()->getIdentity())
                ->query()
                ->fetchColumn()
        ;
        if ($row)
            return true;
        else
            return false;
    }

    public function comments() {
        return new Engine_ProxyObject($this, Engine_Api::_()->getDbtable('comments', 'core'));
    }

    public function likes() {
        return new Engine_ProxyObject($this, Engine_Api::_()->getDbtable('likes', 'core'));
    }

}